package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisidWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisidWorker redisidWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    /**
     * 加载lua脚本
     */
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT=new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);

    }
    /**
     * 阻塞队列
     */
    private BlockingQueue<VoucherOrder> ordersTasks =new ArrayBlockingQueue<>(1024 * 1024);
    /**
     * 线程池
     */
    private static  final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    private IVoucherOrderService proxy;

    /**
     * 类加载完，就立即执行
      */
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    /**
     * 异步线程，从阻塞队列中取出订单信息，执行保存订单到数据库
     */
    private  class VoucherOrderHandler implements  Runnable{
        @Override
        public void run() {
            //不会死循环，阻塞队列拿不出东西会等待
            while(true) {
                try {
                    //获取队列的订单信息
                    VoucherOrder voucherOrder = ordersTasks.take();
                    handleVoucherOrder(voucherOrder);
                } catch (InterruptedException e) {
                    log.info("处理订单异常",e);
                }
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        //创建锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁
        boolean flag = lock.tryLock();
        if(!flag) {
            //获取锁失败
            log.error("不允许重复下单");
            return;
        }
        try {
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    /**
     * 下单秒杀卷
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) throws InterruptedException {
       // 执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), UserHolder.getUser().getId().toString()
        );
     // 判断返回结果，可看lua脚本
        int r = result.intValue();
        if(r != 0) {
           return Result.fail(r == 1?"库存不足":"不可重复下单");
        }
        long order = redisidWorker.nextid("order");

        //        5.秒杀成功了，生成 优惠卷订单
        VoucherOrder voucherOrder=new VoucherOrder();
//        5.1订单id
        long orderid = redisidWorker.nextid("order");
        voucherOrder.setId(orderid);
//        5.2优惠卷id
        voucherOrder.setVoucherId(voucherId);
//        5.3用户id
        voucherOrder.setUserId(UserHolder.getUser().getId());
        //放入阻塞队列
        ordersTasks.add(voucherOrder);
        //获取代理对象  在这里是避免，开启新线程异步处理的时候，拿不到代理对象，事务失效
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(order);
    }

    /**
     * 业务执行
     * @param voucherOrder
     */
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //        一人一单，不能你一个人抢好多卷把
        int count = query()
                .eq("voucher_id", voucherOrder.getVoucherId())
                .eq("user_id", voucherOrder.getUserId())
                .count();
        if(count>0){
            log.error("不可重复下单！");
            return;
        }
//       乐观锁CAS法
        boolean flag = seckillVoucherService.update()
                .setSql("stock = stock -1") //set stock = stock-1
                .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock",0) //where voucher_id =? and stock > 0
                .update();
        if(!flag){
           log.error("库存不足惹！");
           return;
        }
        //创建订单
        save(voucherOrder);
    }

    /**
     * 下单秒杀卷
     * @param voucherId
     * @return
     */
//    @Override
//    public Result seckillVoucher(Long voucherId) throws InterruptedException {
////        1.查询优惠卷
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        if(seckillVoucher==null) {
//            throw  new BeseException("游优惠卷不存在，请刷新页面");
//        }
////        2.秒杀是否开始
//        LocalDateTime now=LocalDateTime.now();
//        if(!now.isAfter(seckillVoucher.getBeginTime())) {
//            return  Result.fail("秒杀时间未到，请等候");
//        }
////        3.秒杀是否结束
//        if(now.isAfter(seckillVoucher.getEndTime())){
//            return Result.fail("秒杀结束，请下次参与");
//        }
////        4.优惠卷的库存够么？
//        Integer stock = seckillVoucher.getStock();
//        if(stock<1){
//            return  Result.fail("秒杀失败，库存不足");
//        }
//        Long userId = UserHolder.getUser().getId();
////        获取锁
////        SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order" + userId, stringRedisTemplate);
////      创建锁对象
//        RLock lock = redissonClient.getLock("lock:order" + userId);
//        /**
//         * 三个参数。第一个代表等待时间，获取失败的话，时间内可重复获取锁
//         * 第二个是锁过期时间，第三个为单位
//         * 空置的话  -1,  -1:意味着30秒,  （s）秒。  意味着，不重入，30s后过期
//         */
//        boolean success = lock.tryLock(1,-1,TimeUnit.SECONDS);
////        获取锁失败
//        if(!success) {
//            return Result.fail("一人只能下一单哦");
//        }
////        成功拿到锁
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
////            释放锁
//            lock.unlock();
//        }
//    }
    /**
     * 业务处理
     *
     */
//     @Transactional
//     public Result createVoucherOrder(Long voucherId) {
//         //        一人一单，不能你一个人抢好多卷把
//         int count = query()
//                 .eq("voucher_id", voucherId)
//                 .eq("user_id", UserHolder.getUser().getId())
//                 .count();
//         if(count>0){
//             return Result.fail("您已下单，不可重复购买");
//         }
// //       乐观锁CAS法
//         boolean flag = seckillVoucherService.update()
//                 .setSql("stock = stock -1") //set stock = stock-1
//                 .eq("voucher_id", voucherId).gt("stock",0) //where voucher_id =? and stock > 0
//                 .update();
//         if(!flag){
//             return Result.fail("库存不足");
//         }
// //        5.秒杀成功了，生成 优惠卷订单
//         VoucherOrder voucherOrder=new VoucherOrder();
// //        5.1订单id
//         long orderid = redisidWorker.nextid("order");
//         voucherOrder.setId(orderid);
// //        5.2优惠卷id
//         voucherOrder.setVoucherId(voucherId);
// //        5.3用户id
//         voucherOrder.setUserId(UserHolder.getUser().getId());
//         voucherOrder.setPayTime(LocalDateTime.now());
//         save(voucherOrder);
//         return Result.ok(orderid);
//     }

}
